const { userModel, goodsModel } = require('../db/index')
const uuid = require('node-uuid')
const dayjs = require('dayjs')
const Token = require('./token')
const jwtKey = '_____WaterCome______arouth:Azhao!'

// 返回token解析结果
function checkToken(req, res) {
    const tokenObj = Token.decryptToken(req.headers.token, jwtKey)
    return tokenObj
}

// 删除一个元素
function deleteArray(model, searchObj, delObj, res,) {
    model.updateOne(
        searchObj,
        {
            "$pull": {
                "myCar": delObj
            }
        }, (err, result) => {
            if (err) {
                return res.send({
                    msg: err.message,
                    state: 500
                })
            } else {
                return res.send({
                    msg: "删除成功",
                    state: 200
                })
            }
        }
    )
}

// 在集合数组内插入一个文档
function updateArray(model, searchObj, updateObj, res) {
    model.updateOne(
        searchObj,
        {
            "$addToSet": {
                "myCar": updateObj
            }
        }, (err, result) => {
            if (err) {
                return res.send({
                    msg: err.message,
                    state: 500
                })
            } else {
                return res.send({
                    msg: "添加成功",
                    state: 200
                })
            }
        }
    )
}

// 查找集合内的数组数据
function search(model, searchObj, ArrayName, res) {
    model.findOne(searchObj, (err, doc) => {
        if (err) {
            return res.send({
                msg: err.message,
                state: 500
            })
        } else {
            if (doc !== null) {
                return res.send({
                    msg: "获取成功",
                    state: 200,
                    data: {
                        arr: doc[ArrayName]
                    }
                })
            }
        }
    })
}

// 获取商品数据
function getGoodsDate(req, res) {
    goodsModel.find({}, (err, docs) => {
        if (err) {
            return res.send({
                msg: err.message,
                state: 500
            })
        } else {
            return res.send({
                msg: "数据获取成功",
                state: 200,
                data: {
                    docs,
                }
            })
        }
    })
}

// 登陆
function login(req, res) {
    const { phone, password } = req.body
    userModel.findOne({ phone, password }, (err, doc) => {
        if (err) {
            return res.send({
                msg: err.message,
                state: 500,
            })
        } else {
            if (doc !== null && phone === doc.phone && password === doc.password) {
                console.log(doc)
                const token = Token.encryptionToken(doc._id, jwtKey)
                userModel.updateOne(
                    {
                        _id: doc._id
                    },
                    {
                        "$set": {
                            token,
                        }
                    },
                    (err, result) => {
                        if (err) {
                            return res.send({
                                msg: err.message,
                                state: 500,
                            })
                        } else {
                            return res.send({
                                msg: "登陆成功",
                                data: {
                                    token,
                                    username: doc.username
                                }
                            })
                        }
                    }
                )
            } else {
                return res.send({
                    msg: "该用户不存在请注册后登陆",
                    state: 200
                })
            }
        }
    })

}

// 注册
function register(req, res) {

    const { phone, username, password } = req.body

    userModel.findOne({ username }, (err, doc) => {
        if (err) {
            return res.send({
                msg: err.message,
                state: 500
            })
        } else {
            if (doc === null) {
                const _id = uuid()
                userModel.create(
                    {
                        _id,
                        username,
                        password,
                        phone
                    }, (err, result) => {
                        if (err) {
                            return res.send({
                                msg: err.message,
                                state: 500
                            })
                        } else {
                            return res.send({
                                msg: "注册成功",
                                state: 200
                            })
                        }
                    }
                )
            } else {
                return res.send({
                    msg: "该用户已存在",
                    state: 200
                })
            }
        }
    })
}

// 获取购物车数据
function searchGoodsIntheCar(req, res) {
    const token = checkToken(req, res)
    if (token === 'tokenKey is error') {
        return res.send({ msg: "未登录" })
    } else {
        search(userModel, { _id: token._id }, 'myCar', res)
    }
}

// 添加到购物车
function addGoods(req, res) {
    const token = checkToken(req, res)
    if (token === 'tokenKey is error') {
        return res.send({ msg: "未登录" })
    } else {
        const item = req.body.item
        item.addTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
        let flag = false
        userModel.findOne({ _id: token._id }, (err, doc) => {
            if (err) {
                return res.send({
                    msg: err.message,
                    state: 500
                })
            } else {
                if (doc !== null) {
                    userModel.findOne({ _id: token._id }, (err, doc) => {
                        doc.myCar.forEach(el => {
                            if (item._id === el._id) {
                                flag = true
                                item.num = el.num
                                item.num++
                            }
                        })

                        if (flag) {
                            userModel.updateOne(
                                { _id: token._id },
                                {
                                    "$pull": {
                                        "myCar": { _id: item._id }
                                    }
                                }, (err, result) => {
                                    if (err) {
                                        return res.send({
                                            msg: err.message,
                                            state: 500
                                        })
                                    } else {
                                        updateArray(userModel, { _id: token._id }, item, res)
                                    }
                                }
                            )
                        } else {
                            item.num = 1
                            updateArray(userModel, { _id: token._id }, item, res)
                        }



                    })
                }
            }
        })

    }


}

// 删除购物车商品
function reduceGoods(req, res) {
    const token = checkToken(req, res)
    if (token === 'tokenKey is error') {
        return res.send({ msg: "未登录" })
    } else {
        const item = req.body.item
        let flag = false
        userModel.findOne({ _id: token._id }, (err, doc) => {
            if (err) {
                return res.send({
                    msg: err.message,
                    state: 500
                })
            } else {
                doc.myCar.forEach(el => {
                    if (el.num > 1) {
                        flag = true
                        item.num = el.num
                        item.num--
                    } else {
                        flag = false
                    }
                })

                if (flag) {
                    userModel.updateOne(
                        { _id: token._id },
                        {
                            "$pull": {
                                "myCar": { _id: item._id }
                            }
                        }, (err, result) => {
                            if (err) {
                                return res.send({
                                    msg: err.message,
                                    state: 500
                                })
                            } else {

                                updateArray(userModel, { _id: token._id }, item, res)
                                flag = false
                            }
                        }
                    )
                } else {
                    deleteArray(userModel, { _id: token._id }, { _id: item._id }, res)
                }
            }
        })
    }
}


// 获取详情页单独一条商品
function getGoodsDetails(req, res) {
    const _id = req.query._id
    goodsModel.findOne({ _id }, (err, doc) => {
        if (err) {
            return res.send({
                msg: err.message,
                state: 500
            })
        } else {
            return res.send({
                msg: "详情页数据获取成功",
                state: 200,
                data: {
                    goods: doc
                }
            })
        }
    })
}


// 添加地址
function addAddress(req, res) {
    const token = checkToken(req, res)
    if (token === 'tokenKey is error') {
        return res.send({ msg: "未登录" })
    } else {
        const { name, phone, address, isDefaul } = req.body
        console.log(req.body)
        userModel.updateOne(
            { _id: token._id },
            {
                "$addToSet": {
                    "addressList": { _id: uuid(), name, phone, address, isDefaul }
                }
            }, (err, result) => {
                if (err) {
                    return res.send({
                        msg: err.message,
                        state: 500
                    })
                } else {
                    return res.send({
                        msg: "添加成功",
                        state: 200
                    })
                }
            }
        )
    }

}


// 获取地址
function getLocationList(req, res) {
    const token = checkToken(req, res)
    if (token === 'tokenKey is error') {
        return res.send({ msg: "未登录" })
    } else {
        search(userModel, { _id: token._id }, 'addressList', res)
    }

}


// 删除地址
function delAddress(req, res) {
    const token = checkToken(req, res)
    if (token === 'tokenKey is error') {
        return res.send({ msg: "未登录" })
    } else {
        const _id = req.body._id
        userModel.updateOne(
            { _id: token._id },
            {
                "$pull": {
                    "addressList": { _id }
                }
            }, (err, result) => {
                if (err) {
                    return res.send({
                        msg: err.message,
                        state: 500
                    })
                } else {
                    return res.send({
                        msg: "删除成功",
                        state: 200
                    })
                }
            }
        )
    }

}


// 修改地址
function updateAddress(req, res) {
    const token = checkToken(req, res)
    if (token === 'tokenKey is error') {
        return res.send({ msg: "未登录" })
    } else {
        const { _id, name, phone, address, isDefaul } = req.body
        let obj = {}
        userModel.findOne({ _id: token._id }, (err, doc) => {
            if (err) {
                return res.send({
                    msg: err.message,
                    state: 500
                })
            } else {
                if (doc.addressList.length !== 0) {
                    doc.addressList.forEach((el, index) => {
                        if (el._id === _id) {
                            obj = el
                            console.log(obj)
                        }
                    })
                }
            }
        })

        if (obj._id === _id || obj.name === name && obj.phone === phone && obj.address === address && obj.isDefaul === isDefaul) {
            return res.send({
                msg: "没有改动",
                state: 200
            })
        } else {
            userModel.updateOne(
                { _id: token._id },
                {
                    "$pull": {
                        "addressList": { _id: obj._id }
                    }
                }, (err, result) => {
                    if (err) {
                        return res.send({
                            msg: err.message,
                            state: 500
                        })
                    } else {
                        userModel.updateOne(
                            { _id: token._id },
                            {
                                "$addToSet": {
                                    "addressList": { _id, name, phone, address, isDefaul }
                                }
                            }, (err, result) => {
                                if (err) {
                                    return res.send({
                                        msg: err.message,
                                        state: 500
                                    })
                                } else {
                                    return res.send({
                                        msg: "修改成功",
                                        state: 200
                                    })
                                }
                            }
                        )
                    }
                }
            )
        }
    }
}


// 获取用户信息
function getUserInfo(req, res) {
    const token = checkToken(req, res)
    if (token === 'tokenKey is error') {
        return res.send({ msg: "未登录" })
    } else {
        userModel.findOne({ _id: token._id }, (err, doc) => {
            if (err) {
                return res.send({
                    msg: err.message,
                    state: 500
                })
            } else {
                const user = {
                    _id: doc._id,
                    username: doc.username,
                    phone: doc.phone,
                    age: doc.age,
                    sex: doc.sex,
                    birthday: doc.birthday,
                    token: doc.token,
                    introduce: doc.introduce
                }

                return res.send({
                    msg: "获取成功",
                    state: 200,
                    data: {
                        user,
                    }
                })

            }
        })
    }
}


// 修改用户信息
function updateUserInfo(req, res) {
    const token = checkToken(req, res)
    if (token === 'tokenKey is error') {
        return res.send({ msg: "未登录" })
    } else {
        const { username, sex, birthday, age, introduce } = req.body
        userModel.updateOne(
            { _id: token._id },
            {
                $set: {
                    username,
                    sex,
                    birthday,
                    age,
                    introduce
                }
            },
            (err, result) => {
                if (err) {
                    return res.send({
                        msg: err.message,
                        state: 500
                    })
                } else {
                    return res.send({
                        msg: "修改成功",
                        state: 200
                    })
                }
            }
        )


    }
}


// 添加订单
function addOrder(req, res) {
    const token = checkToken(req, res)
    if (token === 'tokenKey is error') {
        return res.send({ msg: "未登录" })
    } else {
        const _id = uuid()
        const addTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
        const { sum, goods, address } = req.body
        userModel.updateOne(
            { _id: token._id },
            {
                "$addToSet": {
                    "myOrder": { _id, addTime, sum, goods, address, }
                }
            }, (err, result) => {
                if (err) {
                    return res.send({
                        msg: err.message,
                        state: 500
                    })
                } else {
                    return res.send({
                        msg: "添加订单成功",
                        state: 200
                    })
                }
            }
        )
    }
}

// 清空购物车
function removeCar(req, res) {
    const token = checkToken(req, res)
    if (token === 'tokenKey is error') {
        return res.send({ msg: "未登录" })
    } else {
        userModel.findOne({ _id: token._id }, (err, doc) => {
            if (err) {
                return res.send({
                    msg: err.message,
                    state: 500
                })
            } else {
                new Promise((resolve, reject) => {
                    if (doc !== null) {
                        let car = doc.myCar
                        car.forEach(el => {
                            userModel.updateOne(
                                { _id: token._id },
                                {
                                    "$pull": {
                                        "myCar": { _id: el._id }
                                    }
                                },
                                (e, result) => {
                                    if (e) {
                                        reject(false)
                                    } else {
                                        resolve(true)
                                    }
                                }
                            )
                        })
                    } else {
                        reject(false)
                    }
                }).then(
                    val => {
                        if (val) {
                            return res.send({
                                msg: '删除成功',
                                state: 200
                            })
                        } else {
                            return res.send({
                                msg: e.message,
                                state: 500
                            })
                        }
                    },
                )
                
            }
        })
    }
}

// 获取订单
function getOrder(req, res) {
    const token = checkToken(req, res)
    if (token === 'tokenKey is error') {
        return res.send({ msg: "未登录" })
    } else {
        userModel.findOne({ _id: token._id }, (err, doc) => {
            if (err) {
                return res.send({
                    msg: err.message,
                    state: 500
                })
            } else {
                if (doc !== null) {
                    return res.send({
                        msg: "获取成功",
                        state: 200,
                        data: {
                            arr: doc.myOrder.reverse()
                        }
                    })
                }
            }
        })
    }

}

// 获取单个订单
function getOnesOrder(req, res) {
    const token = checkToken(req, res)
    let data = null
    if (token === 'tokenKey is error') {
        return res.send({ msg: "未登录" })
    } else {
        const _id = req.query._id
        userModel.findOne({ _id: token._id }, (err, doc) => {
            if (err) {
                return res.send({
                    msg: err.message,
                    state: 500
                })
            } else {
                if (doc !== null) {
                    const order = doc.myOrder
                    order.forEach(el => {
                        if (el._id === _id) {
                            data = el
                        }
                    })
                    return res.send({
                        msg: "获取成功",
                        data,
                    })
                }
            }
        })
    }
}

// 删除订单
function delOrder(req, res) {
    const token = checkToken(req, res)
    if (token === 'tokenKey is error') {
        return res.send({ msg: "未登录" })
    } else {
        const _id = req.body._id
        userModel.updateOne(
            { _id: token._id },
            {
                "$pull": {
                    "myOrder": { _id }
                }
            }, (err, result) => {
                if (err) {
                    return res.send({
                        msg: err.message,
                        state: 500
                    })
                } else {
                    return res.send({
                        msg: "删除成功",
                        state: 200
                    })
                }
            }
        )
    }
}

// 获取品牌商品数据
function getBrandGoods(req, res) {
    const brand = req.query.brand
    goodsModel.find({ brand }, (err, docs) => {
        if (err) {
            return res.send({
                msg: err.message,
                state: 500
            })
        } else {
            return res.send({
                msg: "获取成功",
                data: {
                    data: docs
                }
            })
        }
    })
}

module.exports = {
    getGoodsDate,
    login,
    register,
    addGoods,
    searchGoodsIntheCar,
    reduceGoods,
    getGoodsDetails,
    addAddress,
    getLocationList,
    delAddress,
    updateAddress,
    getUserInfo,
    updateUserInfo,
    addOrder,
    removeCar,
    getOrder,
    getOnesOrder,
    delOrder,
    getBrandGoods
}

